import React, { FC, useEffect, useState, useRef } from 'react'
import Taro, { useRouter, SocketTask, useDidHide, useDidShow } from '@tarojs/taro'
import { View, Image, ScrollView, Text, Input } from '@tarojs/components'
import { AtIcon } from 'taro-ui'
import Photograph from '@/components/Photograph/index'
import api from '@/services/config/index'
import { showToast, getUserInfo } from '@/utils/common'
import './index.scss'

interface OrderState {
  title: string
  //订单id
  orderId: string
  // 物品图片
  imagePath: Array<{
    imagePath: string
  }>
  buttonList: {
    promptInformation: string
  }
}
type Message = Array<{
  messageId: string
  content: string
  fromUserId: string
  type: string | number
}>
interface UserInfo {
  userId: string
  // 用户图像
  avatarUrl: string
}
const ChartOnline: FC = () => {
  const router = useRouter()
  const { shareId, name, orderId } = router.params
  // 订单信息
  const [orderState, setOrderState] = useState<OrderState>({
    title: '',
    orderId: '',
    imagePath: [
      {
        imagePath: ''
      }
    ],
    buttonList: {
      promptInformation: ''
    }
  })
  const [news, setNews] = useState<string>('') //input输入的消息
  const socketOpen = useRef<boolean>(false) // 是否连接上
  const socketTask = useRef<SocketTask>() // 建立通讯后返回的实例
  const socketMsgQueue = useRef<Message>([]) //暂存的消息队列
  const userInfo = useRef<UserInfo>({
    userId: '',
    avatarUrl: ''
  })
  // 消息记录
  const [message, setMessage] = useState<Message>([
    {
      messageId: '',
      content: '',
      fromUserId: '',
      type: ''
    }
  ])
  const [otherAvaurl, setOtherAvaurl] = useState<string>('') // 聊天对方的图像
  const [tolast, settolast] = useState<string>('item0') // 哪个方向滚动到该元素
  const scrollToBtm = useRef<boolean>(true) // 是否需要滚动到最底部
  const [refresherTriggered, setrefresherTriggered] = useState(true)
  const [ressource, setRessource] = useState<boolean>(false) // 底部上传照片
  const pageNoRef = useRef(1) // 当前页
  const isFinished = useRef(false) //是否加载完
  const pageSizeRef = useRef(10) // 一页多少条

  // 发送信息
  function sendSocketMessage(msg, type = 1) {
    console.log('发送的信息', msg)
    if (!msg) {
      return
    }
    if (socketOpen.current) {
      ;(socketTask.current as SocketTask).send({
        data: JSON.stringify({
          content: msg,
          fromUserId: userInfo.current.userId,
          orderId: orderState.orderId || orderId,
          state: 1,
          type
        })
      })
    } else {
      socketMsgQueue.current.push(msg)
    }
  }
  // 建立联系
  function connectSocket() {
    Taro.connectSocket({
      url: 'ws://192.168.1.46:9501'
    }).then((task) => {
      task.onOpen(function() {
        console.log('onOpen')
        socketTask.current = task
        socketOpen.current = true
        for (let i = 0; i < socketMsgQueue.current.length; i++) {
          sendSocketMessage(socketMsgQueue[i])
        }
      })
      task.onMessage(function(msg) {
        const flag = /\{/.test(msg.data)
        if (flag) {
          const data = JSON.parse(msg.data)
          scrollToBtm.current = true
          setMessage((pre) => {
            return pre.concat(data)
          })
        }
      })
    })
  }

  // 查询订单详情
  function getOrderDetail() {
    api['itemSharing/getOrderDetail']({ orderId }).then((res) => {
      const data = res.data[0]
      setOrderState(data)
      data.buyUser.buyUserId === userInfo.current.userId
        ? setOtherAvaurl(data.sellUser.sellAatarUrl)
        : setOtherAvaurl(data.buyUser.buyAatarUrl)
    })
  }

  // 查询消息记录
  function getChatMessageList(_orderId?) {
    if (isFinished.current) {
      showToast('没有更多数据了')
      setrefresherTriggered(false)
      return
    }
    api['chartOnline/getChatMessageList'](
      {
        pageSize: pageSizeRef.current,
        pageNo: pageNoRef.current,
        orderId: _orderId || orderId
      },
      { noShowLoading: true, noShowDefaultError: true }
    )
      .then((res) => {
        const data = res.data
        if (data.length > 0) {
          const _data = data.reverse()
          pageNoRef.current += 1
          const _message = [..._data, ...message]
          setMessage(_message)
        } else {
          isFinished.current = true
        }
        if (pageNoRef.current > 2) {
          setrefresherTriggered(false)
        }
      })
      .catch(() => {
        setrefresherTriggered(false)
      })
  }
  // 初始化订单
  function initOrderState() {
    api['chartOnline/orderState']({ shareId: shareId }).then((res) => {
      const data = res.data[0]
      setOrderState(data)
      getChatMessageList(data.orderId)
      data.buyUser.buyUserId === userInfo.current.userId
        ? setOtherAvaurl(data.sellUser.sellAatarUrl)
        : setOtherAvaurl(data.buyUser.buyAatarUrl)
    })
  }
  // 关闭socket
  function socketClose() {
    ;(socketTask.current as SocketTask).close({
      success: () => {
        console.log('socket 关闭成功！')
      },
      fail: () => {
        console.log('socket 失败！')
      }
    })
  }
  // 预览图片
  function previewImage(current) {
    Taro.previewImage({
      current, // 当前显示图片的http链接
      urls: [current] // 需要预览的图片http链接列表
    })
  }
  useEffect(() => {
    userInfo.current = getUserInfo()
    if (name) {
      Taro.setNavigationBarTitle({ title: name })
    }
    if (shareId) {
      initOrderState()
    }
    if (orderId) {
      getChatMessageList()
      getOrderDetail()
    }
    return () => {
      socketClose()
    }
  }, [])

  useEffect(() => {
    if (scrollToBtm.current) {
      settolast(`item${message.length - 1}`)
    }
  }, [message])

  useDidShow(() => {
    connectSocket()
  })
  useDidHide(() => {
    socketClose()
  })

  return (
    <View className='chartOnline'>
      {/* 商品信息 */}
      <View className='chartOnline-itemsInfo tc-flex white-bgc'>
        <Image
          src={orderState.imagePath[0].imagePath}
          className='chartOnline-itemsInfo__imagePath'
        ></Image>
        <View className='chartOnline-itemsInfo__info'>
          <View className='chartOnline-itemsInfo__info-title'>{orderState.title}</View>
          <View className='chartOnline-itemsInfo__info-tips'>交易前聊一聊</View>
        </View>
        {orderState.buttonList.promptInformation && (
          <View
            className='chartOnline-itemsInfo__btn ct ellipsis'
            onClick={() => {
              Taro.navigateTo({
                url: '/pages/ItemSharing/OrderDetail/index?orderId=' + orderState.orderId
              })
            }}
          >
            {orderState.buttonList.promptInformation}
          </View>
        )}
      </View>
      {/* 聊天内容 */}
      <View className='chartOnline-main  grey-bgc'>
        <ScrollView
          scrollY
          scrollAnchoring
          scrollIntoView={tolast}
          refresherDefaultStyle='white'
          refresherBackground='#e2e2e2'
          refresherEnabled
          refresherTriggered={refresherTriggered}
          onRefresherRefresh={() => {
            scrollToBtm.current = false
            getChatMessageList()
          }}
          onRefresherRestore={() => {
            setrefresherTriggered(true)
          }}
          className='chartOnline-main-scroll'
        >
          <View className='container'>
            {message.map((item, index) => {
              return item.fromUserId === userInfo.current.userId ? (
                <View
                  className='chartOnline-main__info flex flex-end'
                  key={item.messageId}
                  id={'item' + index}
                >
                  {Number(item.type) === 1 ? (
                    <View className='chartOnline-main__info-txt'>
                      <Text>{item.content}</Text>
                      <View className='txt-decorate txt-decorate-posright'></View>
                    </View>
                  ) : (
                    <Image
                      className='chartOnline-main__info-txtimg'
                      src={item.content}
                      onClick={previewImage.bind(null, item.content)}
                    ></Image>
                  )}
                  <Image
                    className='chartOnline-main__info-ava'
                    src={userInfo.current.avatarUrl}
                    onClick={previewImage.bind(null, userInfo.current.avatarUrl)}
                  ></Image>
                </View>
              ) : (
                item.messageId && (
                  <View
                    className='chartOnline-main__info flex flex-start'
                    key={item.messageId}
                    id={'item' + index}
                  >
                    <Image
                      className='chartOnline-main__info-ava'
                      src={otherAvaurl}
                      onClick={previewImage.bind(null, otherAvaurl)}
                    ></Image>
                    {Number(item.type) === 1 ? (
                      <View className='chartOnline-main__info-txt'>
                        <Text>{item.content}</Text>
                        <View className='txt-decorate txt-decorate-posleft'></View>
                      </View>
                    ) : (
                      <Image
                        className='chartOnline-main__info-txtimg'
                        src={item.content}
                        onClick={previewImage.bind(null, item.content)}
                      ></Image>
                    )}
                  </View>
                )
              )
            })}
          </View>
        </ScrollView>
      </View>
      {/* 底部聊天输入框 */}
      <View className='chartOnline-bottom white-bgc tc-flex white-bgc'>
        <View>
          <View className='chartOnline-bottom__oper tc-flex '>
            <Input
              name='value'
              type='text'
              placeholder='请输入消息'
              value={news}
              adjustPosition
              cursorSpacing={100}
              confirmHold
              onInput={(e) => {
                setNews(e.detail.value)
              }}
              onFocus={() => {
                setRessource(false)
              }}
              onConfirm={() => {
                scrollToBtm.current = true
                sendSocketMessage(news)
                setNews('')
              }}
              className='chartOnline-bottom__oper-input'
            />
            <View
              className='chartOnline-bottom__oper-sendout'
              onClick={() => {
                scrollToBtm.current = true
                sendSocketMessage(news)
                setNews('')
              }}
            >
              发送
            </View>
            <AtIcon
              prefixClass='icon'
              value='gnxz'
              size='28'
              color='#333333'
              onClick={() => {
                setRessource(!ressource)
              }}
            ></AtIcon>
          </View>
          {ressource && (
            <View className='chartOnline-bottom__ressource b-top'>
              <Photograph
                name='slot'
                onHandChange={(file) => {
                  sendSocketMessage(file[0].uploadUrl, 2)
                  setRessource(false)
                }}
              >
                <View className='chartOnline-bottom__ressource-type flex'>
                  <AtIcon prefixClass='icon' value='tpsc' size='35' color='#333333'></AtIcon>
                  <View className='font26'>图片</View>
                </View>
              </Photograph>
            </View>
          )}
        </View>
      </View>
    </View>
  )
}

export default ChartOnline
